package com.wkm.chainchain.pbft.PBFTBlockchainNode;

import com.wkm.chainchain.pbft.node.AllNodeInfo;
import com.wkm.chainchain.pbft.node.Node;
import com.wkm.chainchain.pbft.p2p.PBFTClient;
import com.wkm.chainchain.pbft.p2p.PBFTServer;
import com.wkm.chainchain.consensusutils.YamlUtil;
import com.wkm.chainchain.websocket.Client;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

import static com.wkm.chainchain.pbft.common.SimulationParameterConst.*;
import static com.wkm.chainchain.state.ConsensusNodeBuildState.*;


/**
 * PBFT主函数 通过输入确定共识节点还是消息发送端口 注意java虚拟机内存的设置 线程开太多容易爆栈 -Xms1024m -Xmx1024m
 */
@Slf4j
public class PBFTBlockchainNode {

    public static void main(String[] args) {
        //读取配置
        YamlUtil yamlUtil = new YamlUtil();
        Map<String, Integer> map = yamlUtil.getYaml("const.yaml");
        INITIAL_PORT = map.get("INITIAL_PORT");
        NODE_AMOUNT = map.get("NODE_AMOUNT");
        CLIENT_PORT = map.get("CLIENT_PORT");

        // 获取当前已经运行的服务端的节点的数量
        int serverRunningNum = getServerRunningNum();
        int port = serverRunningNum + INITIAL_PORT;

        PBFTServer.getInstance(port);
        //初始化当前节点
        Node node = Node.getInstance();
        node.setIndex(port - INITIAL_PORT);
        node.setIp("127.0.0.1");
        node.setPort(port);
        AllNodeInfo.P2P_NODE_ARRAYS[node.getIndex()] = node;

        // 已经运行起来，给节点数量加1
        addOneServerRunningNum();

        do {
            try {
                Thread.sleep(sleepTimeMills);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        } while (getServerRunningNum() < NODE_AMOUNT);

        Client client = PBFTClient.getInstance();
        //与消息发送客户端建立连接
        client.connectRequestClient();
        //初始化 连接所有的P2P节点
        for (int i = 0; i < NODE_AMOUNT; i++) {
            //与当前节点以外的节点建立连接
            if (node.getPort() != (INITIAL_PORT + i)) {
                client.connectPeer("ws://localhost:" + (INITIAL_PORT + i));
            }
        }
    }
}


